const app = getApp()
var xrSdk = require('../../../vendor/hope-sdk/index.js');
var xrRequest = require('../../../vendor/hope-sdk/core/request.js');
var config = require('../../../config.js');
const util = require('../../../utils/util.js')
Page({
  data: {
    serverUrl: config.service.hostUrl,
    searchKey: "", // 搜索关键词
    categoryID:0,  // 当前的分类ID 
    width: 200, //header宽度
    height: 64, //header高度
    inputTop: 0, //搜索框距离顶部距离
    arrowTop: 0, //箭头距离顶部距离
    dropScreenH: 0, //下拉筛选框距顶部距离
    attrData: [],
    attrIndex: -1,
    dropScreenShow: false,
    scrollTop: 0,
    tabIndex: 0, //顶部筛选索引
    isList: false, //是否以列表展示  | 列表或大图
    drawer: false,
    drawerH: 0, //抽屉内部scrollview高度
    order:'',
    selectedName: "综合",
    selectH: 0,
    dropdownList: [{
      name: "综合",
      selected: true
    }, {
      name: "价格升序",
      selected: false,
    }, {
      name: "价格降序",
      selected: false,
    }],
    attrArr: [{
      name: "新品",
      selectedName: "新品",
      isActive: false,
      list: []
    }, {
      name: "热卖",
      selectedName: "热卖",
      isActive: false,
      list: []
    }, {
      name: "推荐",
      selectedName: "推荐",
      isActive: false,
      list: []
      },{
        name: "分类",
        selectedName: "分类",
        isActive: false,
        list: []
    }],
    productList: [],
    pageIndex: 1,
    loadding: false,
    pullUpOn: true,
    noContent:false,
    isFirst:true
  },
  onLoad: function (options) {
    let obj = wx.getMenuButtonBoundingClientRect();
    this.setData({
      width: obj.left,
      height: obj.top + obj.height + 8,
      inputTop: obj.top + (obj.height - 30) / 2,
      arrowTop: obj.top + (obj.height - 32) / 2,
      searchKey: options.searchKey || "",
      categoryID: options.categoryID || 0
    }, () => {
      wx.getSystemInfo({
        success: (res) => {
          this.setData({
            //略小，避免误差带来的影响
            dropScreenH: this.data.height * 750 / res.windowWidth + 186,
            drawerH: res.windowHeight - res.windowWidth / 750 * 100 - this.data.height
          })
        }
      });

      this.initCategory();
      this.initList();
    });
  },
  initCategory:function(e){
    var that = this;
    xrRequest.request(app,{
      url: config.service.categoryThreeList,
      login: false,
      data: {
        cid: that.data.categoryID
      },
      success: function (res) {
        if(res.data.code == 1 ){
          console.log(res);
          let rows     = res.data.data;
          for (let item of rows) {
            if (item.id == that.data.categoryID){
              item.selected = true;
              item.isActive = true;
              that.setData({
                [`attrArr[3].isActive`]    : true,
                [`attrArr[3].selectedName`]: item.name
              });

            }else{
              item.selected = false;
              item.isActive = false;
            }
          }
          let list = `attrArr[3].list`;
          that.setData({
            [list]: rows
          });
        }
      }
    });
  },
  onPullDownRefresh: function () {
    this.initData();
    this.initList();
  },
  initData:function(){
    this.setData({
      productList: [],
      pageIndex: 1,
      pullUpOn: true,
      loadding: true,
      noContent:false
    })
  },
  initList:function(){
    var that = this;
    var params = that.getParams();
    xrRequest.request(app,{
      url: config.service.goodsList,
      login: false,
      data: params,
      success: function (res) {
        if (res.data.data.has_more == false) {
          that.setData({
            pullUpOn: false
          })
        }
        that.setData({
          productList: that.data.productList.concat(res.data.data.data),
          pageIndex: that.data.pageIndex + 1,
          loadding: false
        })
        wx.stopPullDownRefresh();
        that.setData({
          noContent: that.data.productList.length == 0
        });
      }
    });
  },
  getParams(){
    var that = this;
    var params = {
      page: that.data.pageIndex,
      page_size: 10
    };
    if (that.data.attrArr[0].isActive){
      params.is_new = 1;
    }
    if (that.data.attrArr[1].isActive) {
      params.is_hot = 1;
    }
    if (that.data.attrArr[2].isActive) {
      params.is_recommend = 1;
    }
    if (!util.isEmpty(that.data.searchKey)) {
      params.keyword = that.data.searchKey;
    }
    if (!util.isEmpty(that.data.categoryID)) {
      params.cid = that.data.categoryID;
    }
    if (!util.isEmpty(that.data.order)) {
      params.order = that.data.order;
    }else if (that.data.dropdownList[0].selected){
      params.order = "default";
    }else if (that.data.dropdownList[1].selected) {
      params.order = "price_asc";
    }else if (that.data.dropdownList[2].selected) {
      params.order = "price_desc";
    }
    return params;
  },
  onReachBottom: function () {
    if (!this.data.pullUpOn) return;
    this.setData({
      loadding: true
    }, () => {
      this.initList();
    })
  },
  btnDropChange: function (e) {
    let index    = e.currentTarget.dataset.index;
    let arr = JSON.parse(JSON.stringify(this.data.attrArr[index].list));
    if (arr.length === 0) {
      let selected = !this.data.attrArr[index].isActive;
      let isActive = `attrArr[${index}].isActive`;
      this.resetAttr();
      this.setData({
        [isActive]: selected
      })
      this.onPullDownRefresh();
    }else{
      if (!util.isNullOrEmpty(this.data.attrData) && this.data.attrData.length > 0){
        arr = this.data.attrData;
      }
      for (let item of arr) {
        item.isActive = item.selected;
      }
      this.setData({
        attrData: arr,
        attrIndex: index,
        dropScreenShow: true
      }, () => {
        this.setData({
          scrollTop: 0
        })
      })
    }
  },
  resetAttr() {
    let arr = this.data.attrArr;
    let i = 0;
    for (let item of arr) {
      if(i == 3) continue;
      item.isActive = false;
      i++;
    }
    this.setData({
      attrArr: arr
    })
  },
  btnSelected: function (e) {
    let index = e.currentTarget.dataset.index;
    let isActive = `attrData[${index}].isActive`;
    this.reset();
    this.setData({
      [isActive]: !this.data.attrData[index].isActive
    })
  },
  reset() {
    let arr = this.data.attrData;
    for (let item of arr) {
      item.isActive = false;
    }
    this.setData({
      attrData: arr
    })
  },
  btnCloseDrop() {
    this.setData({
      scrollTop: 0,
      dropScreenShow: false,
      attrIndex: -1
    })
  },
  btnSure: function () {
    let index    = this.data.attrIndex;
    let arr      = this.data.attrData;
    let active   = false;
    let attrName = "";
    let attrId   = 0;
    //这里只是为了展示选中效果,并非实际场景
    let i = 0;
    for (let item of arr) {
      let selected = `attrData[${i}].selected`;
      if (item.isActive) {
        active = true;
        attrName += attrName ? ";" + item.name : item.name;

        attrId = item.id;
        this.setData({
          [selected]: true
        })
      }else{
        this.setData({
          [selected]: false
        })
      }
      i++;
    }
    let isActive     = `attrArr[${index}].isActive`;
    let selectedName = `attrArr[${index}].selectedName`;
    this.btnCloseDrop();
    this.setData({
      categoryID: attrId,
      [isActive]: active,
      [selectedName]: attrName
    });
    this.onPullDownRefresh();
  },
  showDropdownList: function () {
    this.setData({
      selectH: 246,
      tabIndex: 0
    })
  },
  hideDropdownList: function () {
    this.setData({
      selectH: 0
    })
  },
  dropdownItem: function (e) {
    let index = e.currentTarget.dataset.index;
    let arr = this.data.dropdownList;
    for (let i = 0; i < arr.length; i++) {
      if (i === index) {
        arr[i].selected = true;
      } else {
        arr[i].selected = false;
      }
    }
    this.setData({
      dropdownList: arr,
      selectedName: index == 0 ? '综合' : '价格',
      selectH: 0
    });
    this.onPullDownRefresh();
  },
  screen: function (e) {
    let index = e.currentTarget.dataset.index;
    if (index == 0) {
      this.showDropdownList();
      this.setData({
        order: ''
      });
      this.onPullDownRefresh();
    } else if (index == 1) {
      this.setData({
        tabIndex: 1,
        order:'recommend'
      });
      this.onPullDownRefresh();
    } else if (index == 2){
      this.setData({
        tabIndex: 2,
        order: 'click_count'
      });
      this.onPullDownRefresh();
    } else if (index == 3) {
      this.setData({
        isList: !this.data.isList
      })
    } else if (index == 4) {
      this.setData({
        drawer: true
      })
    }
  },
  back: function () {
    wx.navigateBack()
  },
  search: function () {
    wx.navigateTo({
      url: '../search/search'
    })
  },
  clear:function(e){
    this.setData({
      searchKey: ''
    });
    this.onPullDownRefresh();
  },
  detail: function (e) {
    wx.navigateTo({
      url: '../info/info?id='+ e.currentTarget.dataset.id
    })
  },
  onShow:function(){
    console.log(123);
    if (!this.data.isFirst){
      this.onPullDownRefresh();
    }
    this.setData({
      isFirst: false
    })
  }
})